#include "uri.h"

URI * split_uri(char *location) {

   URI *uri;
   char *ptr,*search,buffer[256];

   uri = (URI *) malloc(sizeof(struct uri_t));

   search = strstr(location, "://");
   if(search != NULL) {
      sprintf(buffer, "%.*s", (int) (search-location), location);
      uri->protocol = strdup(buffer);
      uritolower(uri->protocol);
      ptr = search + (strlen("://"));
   } else {
      uri->protocol = strdup("http");
      ptr = location;
   }

   search = strchr(ptr, '/');
   if(search != NULL) {
      sprintf(buffer, "%.*s", (int) (search-ptr), ptr);
      uri->host = strdup(buffer);
      ptr = search;
   } else {
      uri->host = strdup(ptr);
      ptr = NULL;
   }

   search = strchr(uri->host, ':');
   if(search != NULL) {
      sprintf(buffer, "%.*s", (int) (strchr(uri->host, '\0') - search), search +1);
      uri->port = atoi(buffer);
      uri->host[ (search - uri->host) ] = '\0';
   } else {
      uri->port = 80;
   }

   if(ptr != NULL)
      uri->resource = strdup(ptr);
   else
      uri->resource = NULL;

   search = strrchr(location, '/');
   if( search != NULL && *(search+1) != '\0') {
      uri->file = new_file(search+1, 0);
   }

   if(uri->resource == NULL) uri->resource = strdup("/");
   uri->progress=0;
   uri->bytes=1;

   return uri;

}

void uritolower(char *uri) {

   int i;

   for(i=0;uri[i]!='\0';i++)
      uri[i] = tolower(uri[i]);

}

char * new_file(char *suggest, int try) {

   if(try != 0) {
      
   }

   if(access(".", W_OK) == -1) {
      return strdup(suggest);
   } else if(access(suggest, F_OK) != -1) {

      char file[200];
      int num;
      num = strlen(suggest)>=198 ? 198 : strlen(suggest);
      sprintf(file, "%.*s#%d", num, suggest, try);
      return new_file(file, try+1);
   } else {
      return strdup(suggest);
   }

}
